<template>
  <div class='roleEdit' id="roleEdit">
    <div class='header'>
      <span class='font18 bold' v-text="data ? $t('config.agent.modifyRole'):$t('configLazyLoad.roleSetting.newAddRole')"></span>
      <el-button class='primary_btn' style='margin-right: 10px' @click='EditCancel'>{{$t('public.cancel')}}</el-button>
      <el-button type='primary' class='primary_btn' @click='EditSave'>{{$t('public.save')}}</el-button>
    </div>
    <div style="height: calc(100vh - 175px);overflow: scroll">
    <el-form ref="roleForm" :model.trim="roleData" labelPosition="left" labelWidth="80px" :rules="rules">
      <el-form-item :label="$t('agentSetting.agentSetting42')" prop="display_name">
        <el-input v-model.trim="roleData.display_name"></el-input>
      </el-form-item>
      <el-form-item :label="$t('agentSetting.agentSetting43')" prop="memo">
        <el-input type="textarea" :rows="3" v-model="roleData.memo"></el-input>
      </el-form-item>
      <el-form-item :label="$t('configLazyLoad.roleSetting.dataAuthority')">
        <p class="scope">
          <span class="scopeName">{{$t('public.call')}}</span>
          <el-select v-model="roleData.scope_in.call">
            <el-option v-for="item in options" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </p>
        <p class="scope">
          <span>{{$t('public.customer')}}</span>
          <el-select v-model="roleData.scope_in.customer">
            <el-option v-for="item in options" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </p>
        <p class="scope">
          <span>{{$t('public.business')}}</span>
          <el-select v-model="roleData.scope_in.business">
            <el-option v-for="item in options" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </p>
        <p class="scope">
          <span>{{$t('public.webchat')}}</span>
          <el-select v-model="roleData.scope_in.chat" value-key="scope_in.chat">
            <el-option v-for="item in options" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </p>
        <p class="scope">
          <span>{{$t('public.mail')}}</span>
          <el-select v-model="roleData.scope_in.email">
            <el-option v-for="item in options" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </p>
        <p class="scope">
          <span>{{$t('public.qualityCheck')}}</span>
          <el-select v-model="roleData.scope_in.qc">
            <el-option v-for="item in options" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </p>
        <p class="scope">
          <span>{{$t('configLazyLoad.roleSetting.questionnaireTitle')}}</span>
          <el-select v-model="roleData.scope_in.question">
            <el-option v-for="item in options" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </p>
        <p class="scope">
          <span>{{$t('public.SMS')}}</span>
          <el-select v-model="roleData.scope_in.sms">
            <el-option v-for="item in options" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </p>
        <p class="scope">
          <span>{{$t('public.workbench')}}</span>
          <el-select v-model="roleData.scope_in.workbench">
            <el-option v-for="item in options" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </p>
        <!--<p class="scope">-->
          <!--<span>{{$t('agentSetting.agentSetting')}}</span>-->
          <!--<el-select v-model="roleData.scope_in.agent">-->
            <!--<el-option v-for="item in options" :label="item.label" :value="item.value"></el-option>-->
          <!--</el-select>-->
        <!--</p>-->
        <p class="tips">
          {{$t('configLazyLoad.roleSetting.myAndMylowerTip')}}
        </p>
      </el-form-item>
      <el-form-item :label="$t('configLazyLoad.roleSetting.featuresAuthority')">
        <el-tree
          style="border: none"
          nodeKey="id"
          :data="funcs"
          :show-checkbox="true"
          :default-expand-all="true"
          ref="tree"
          :highlight-current="true"
          @check="checkChange"
          :props="defaultProps"
        >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <el-popover
            placement="right-end"
            width="200"
            trigger="hover"
            content="此权限与 工单-批量分配工单 权限互不影响"
            v-if="data.id == 'func_not_allow_change_business_master'"
            >
            <i class="iconfont icon-wenzishuoming" slot="reference"></i>
          </el-popover>
        </span>
        </el-tree>
      </el-form-item>
    </el-form>
    </div>
  </div>
</template>

<script>
  import {deepClone} from '@/utils/m7Utils'
  export default {
    name: 'roleEdit',
    data () {
      return {
        autoqcCheck: false,
        videoSetCheck: false,
        flag: this.$store.getters.isEcommerce ? 'ecommerce' : 'kf',
        funcs: [],
        roleData: {
          scope_out: {
            'call': 'level',
            'customer': 'level',
            'business': 'level',
            'custTask': 'level',
            'custApproval': 'level',
            'sms': 'level'
          },
          scope_in: {
            call: 'level',
            customer: 'level',
            business: 'level',
            chat: 'level',
            email: 'level',
            qc: 'level',
            question: 'level',
            sms: 'level',
            workbench: 'all',
          },
          scope: 'level',
          limits_in: [],
          memo: '',
          display_name: ''
        },
        options: [
          {
            label: this.$t('public.myAndMylower'),
            value: 'level'
          }, {
            label: this.$t('configLazyLoad.roleSetting.allPerson'),
            value: 'all'
          }, {
            label: this.$t('public.ownerDept'),
            value: 'dept'
          }, {
            label: this.$t('public.ownerAndMyLowerDept'),
            value: 'deptLevel'
          }
        ],
        rules: {
          display_name: [
            {required: true, message: this.$t('validate.required'), trigger: 'blur'}
          ]
        },
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        limitStore: {},
        funcsStore: '',
        funcsArray: [],
        simpleMapToOld: [
          {
            old: 'company_identity',
            simple: 'simple_company_identity'
          }, {
            old: 'account_config',
            simple: 'simple_account_config'
          }, {
            old: 'func_dept_add',
            simple: 'simple_func_dept_add'
          }, {
            old: 'func_dept_delete',
            simple: 'simple_func_dept_delete'
          }, {
            old: 'func_dept_update',
            simple: 'simple_func_dept_update'
          }, {
            old: 'func_dept_move',
            simple: 'simple_func_dept_move'
          }, {
            old: ['func_dept_move', 'func_dept_update', 'func_dept_delete', 'func_dept_add'],
            simple: 'simple_dept_config'
          }, {
            old: 'dept_config',
            simple: ['simple_func_dept_move', 'simple_func_dept_update', 'simple_func_dept_delete', 'simple_func_dept_add']
          }, {
            old: 'dept_config',
            simple: 'simple_dept_config'
          }, {
            old: 'channel_skill_group',
            simple: ['simple_channel_call', 'simple_channel_webchat', 'simple_channel_email']
          }, {
            old: 'channel_skill_group',
            simple: 'simple_channel_skill_group'
          }, {
            old: 'wechat_insert',
            simple: 'simple_wechat_insert'
          }, {
            old: 'wxmini_insert',
            simple: 'simple_wxmini_insert'
          }, {
            old: 'website_insert',
            simple: 'simple_website_insert'
          }, {
            old: 'app_insert',
            simple: 'simple_app_insert'
          }, {
            old: 'weibo_insert',
            simple: 'simple_weibo_insert'
          }, {
            old: ['weibo_insert', 'app_insert', 'website_insert', 'wxmini_insert', 'wechat_insert'],
            simple: 'simple_online_joinin'
          }, {
            // 在线全局设置
            old: 'website_global_config',
            simple: ['simple_finish_webchat_config', 'simple_website_satisfaction_config', 'simple_public_quick_reply_config', 'simple_webchat_blacklist_config']
          }, {
            // 在线全局设置总计
            old: 'website_global_config',
            simple: 'simple_website_global_config'
          }, {
            old: 'black_red_list',
            simple: 'simple_black_red_list'
          }, {
            old: 'call_config_label',
            simple: 'simple_call_config_label'
          }, {
            old: 'call_satisfaction_config',
            simple: 'simple_call_satisfaction_config'
          }, {
            old: ['call_satisfaction_config', 'call_config_label', 'black_red_list'],
            simple: 'simple_call_center'
          }, {
            old: 'call_config',
            simple: ['simple_call_satisfaction_config', 'simple_call_config_label', 'simple_black_red_list']
          }, {
            old: 'show_system_notice',
            simple: 'simple_show_system_notice'
          }, {
            old: 'create_system_notice',
            simple: 'simple_create_system_notice'
          }, {
            old: 'edit_system_notice',
            simple: 'simple_edit_system_notice'
          }, {
            old: 'delete_system_notice',
            simple: 'simple_delete_system_notice'
          }, {
            old: ['delete_system_notice', 'edit_system_notice', 'create_system_notice', 'show_system_notice'],
            simple: 'simple_system_notice'
          }, {
            old: 'system_notice',
            simple: ['simple_delete_system_notice', 'simple_edit_system_notice', 'simple_create_system_notice', 'simple_show_system_notice']
          },
          {
            old: ['operate_log', 'operate_log_data_recovery'],
            simple: 'simple_nav_operate_log'
          },
          {
            old: 'nav_operate_log',
            simple: ['simple_operate_log', 'simple_operate_log_data_recovery']
          },
          {
            old: 'operate_log',
            simple: 'simple_operate_log'
          },
          {
            old: 'operate_log_data_recovery',
            simple: 'simple_operate_log_data_recovery'
          }
        ]
      }
    },
    props: ['data'],
    watch: {
      data () {
        this.getRoleDetails()
      }
    },
    methods: {
      checkChange (data, chooseArray) {
        let chooseId = data.id
        let isChoose = chooseArray.checkedKeys.indexOf(chooseId) > -1
        console.log(chooseId, isChoose)
        if (data.id.indexOf('autoqc') > -1) {
          console.log(data)
          let checkKeys = chooseArray.checkedKeys || []
          for (let i = 0; i < checkKeys.length; i++) {
            if (checkKeys[i].indexOf('autoqc') > -1) {
              if (!this.autoqcCheck) {
                this.$message.success(this.$t('configLazyLoad.roleSetting.quaQualityContent'))
                this.autoqcCheck = true
              }
              break
            }
          }
        }
        if (data.id === 'video_insert') {
          let checkKeys = chooseArray.checkedKeys || []
          for (let i = 0; i < checkKeys.length; i++) {
            if (checkKeys[i] === 'video_insert') {
              if (!this.videoSetCheck) {
                this.$message.success(this.$t('configLazyLoad.roleSetting.videoSetContent'))
                this.videoSetCheck = true
              }
              break
            }
          }
        }
        if (chooseId === 'simple_config') {
          this.simpleMapToOld.forEach((item) => {
            if (item.simple && typeof item.simple === 'string') {
              let data = {
                id: item.simple
              }
              this.checkChange(data, chooseArray)
            } else if (item.simple && typeof item.simple === 'object') {
              item.simple.forEach((sim) => {
                let data = {
                  id: sim
                }
                this.checkChange(data, chooseArray)
              })
            }
          })
          return
        }
        if (chooseId === 'nav_config') {
          let aloneSimple = ['simple_config_guide']
          this.simpleMapToOld.forEach((item) => {
            if (item.old && typeof item.old === 'string') {
              let data = {
                id: item.old
              }
              this.checkChange(data, chooseArray)
            }
          })
          aloneSimple.forEach((alone) => {
            this.$refs.tree.setChecked(alone, isChoose)
          })
          return
        }
        this.simpleMapToOld.forEach((item) => {
          if (item.old === chooseId && typeof item.old === 'string') {
            // 选中的为复杂版一对一
            if (item.simple && typeof item.simple === 'string') {
              // 一对一对应
              this.$refs.tree.setChecked(item.simple, isChoose)
            } else if (item.simple && typeof item.simple === 'object' && item.simple.length > 0) {
              // 一对多
              item.simple.forEach((sim) => {
                this.$refs.tree.setChecked(sim, isChoose)
              })
            }
          } else if (typeof item.old === 'object' && item.old.indexOf(chooseId) > -1) {
            // 选中的为复杂版多对一
            if (isChoose) {
              // 多对一选中 直接选中简单版对应
              this.$refs.tree.setChecked(item.simple, isChoose)
            } else {
              // 多对一取消 判断是否全部取消去取消简单版
              let allChoose = this.$refs.tree.getCheckedKeys()
              let chooseFlag = true
              item.old.forEach((old) => {
                if (allChoose.indexOf(old) > -1) {
                  chooseFlag = false
                }
              })
              if (chooseFlag) {
                this.$refs.tree.setChecked(item.simple, false)
              }
            }
          } else if (item.simple === chooseId) {
            // 选中的为简单版一对一
            if (item.old && typeof item.old === 'string') {
              console.log(item.old, isChoose)
              this.$refs.tree.setChecked(item.old, isChoose)
            } else if (item.old && typeof item.old === 'object' && item.old.length > 0) {
              // 选中为简单版一对多
              // 一对多
              item.old.forEach((old) => {
                this.$refs.tree.setChecked(old, isChoose)
              })
            }
          } else if (typeof item.simple === 'object' && item.simple.indexOf(chooseId) > -1) {
            // 选中为简单版多对一
            if (isChoose) {
              // 多对一选中 直接选中复杂版对应
              this.$refs.tree.setChecked(item.old, isChoose)
            } else {
              // 多对一取消 判断是否全部取消去取消复杂版
              let allChoose = this.$refs.tree.getCheckedKeys()
              let chooseFlag = true
              item.simple.forEach((sim) => {
                if (allChoose.indexOf(sim) > -1) {
                  chooseFlag = false
                }
              })
              if (chooseFlag) {
                this.$refs.tree.setChecked(item.old, false)
              }
            }
          }
        })
      },
      EditCancel () {
        this.$emit('close')
      },
      EditSave () {
        this.$refs.roleForm.validate((valid) => {
          if (valid) {
            this.limitStore = this.$refs.tree.getCheckedKeys()
            let array = deepClone(this.limitStore)
            array.forEach((id) => {
              this.saveFormat(id)
            })
            this.checkAdvance()
            this.roleData.limits_in = this.limitStore
            if (this.roleData.limits_in.indexOf('nav_workbench') === -1) {
              this.roleData.limits_in.push('nav_workbench')
            }
            console.log(this.roleData.limits_in.indexOf('ai_xbot_robot_config') !== -1)
            if (this.roleData.limits_in.indexOf('ai_xbot_robot_config') !== -1) {
              this.$store.dispatch('xbotCreateAccount')
            }
            this.roleData.flag = this.flag
            if (this.data) {
              this.$store.dispatch('updateRole', this.roleData).then((res) => {
                if (res.success) {
                  this.$message.success(this.$t('business.updateSuccess'))
                  this.$emit('saveDone')
                }
              })
            } else {
              this.$store.dispatch('addRole', this.roleData).then((res) => {
                if (res.success) {
                  this.$message.success(this.$t('config.customer.addSucc'))
                  this.$emit('saveDone')
                }
              })
            }
          }
        })
      },
      saveFormat (id) {
        if (this.funcsStore[id].label.indexOf('_') !== -1) {
          let father = this.funcsArray.find((func) => {
            return func.label === this.funcsStore[id].label.slice(0, this.funcsStore[id].label.lastIndexOf('_'))
          })
          if (this.limitStore.indexOf(father.id) === -1) {
            this.limitStore.push(father.id)
          }
          if (father.label.indexOf('_') !== -1) {
            this.saveFormat(father.id)
          }
        }
      },
      getRoleDetails () {
        document.getElementById('roleEdit').parentNode.scrollTop = 0
        if (this.data) {
          this.$store.dispatch('showRoleEdit', {_id: this.data._id, flag: this.flag}).then((res) => {
            if (res.success) {
              if (this.funcsStore === '') {
                this.funcsStore = {}
                res.funcs.forEach((func, index) => {
                  this.funcsFormat(func, index)
                })
              }
              this.funcs = res.funcs
              this.roleData._id = res.role._id
              this.roleData.display_name = res.role.display_name
              this.roleData.scope_in = res.role.scope_in
              let workbench = this.roleData.scope_in.workbench ? this.roleData.scope_in.workbench : 'all'
              this.$set(this.roleData.scope_in, 'workbench', workbench)
              this.roleData.scope_out = res.role.scope_out
              this.roleData.scope = res.role.scope
              this.roleData.limits_in = res.role.limits_in
              this.roleData.memo = res.role.memo
              this.limitStore = deepClone(res.role.limits_in)
              this.getAutoqcAndVideoCheck(res.role.limits_in)
              this.oldRoleFormat(this.limitStore, this.funcs)
              this.roleData.limits_in = this.limitStore
              this.$refs.tree.setCheckedKeys(this.roleData.limits_in)
            }
          })
        } else {
          this.$store.dispatch('showRoleAdd', {flag: this.flag}).then((res) => {
            this.roleData = {
              scope_out: {
                'call': 'level',
                'customer': 'level',
                'business': 'level',
                'custTask': 'level',
                'custApproval': 'level',
                'sms': 'level'
              },
              scope_in: {
                call: 'level',
                customer: 'level',
                business: 'level',
                chat: 'level',
                email: 'level',
                qc: 'level',
                question: 'level',
                sms: 'level',
                workbench: 'all'
              },
              scope: 'level',
              limits_in: [],
              memo: '',
              display_name: ''
            }
            if (res.success) {
              if (this.funcsStore === '') {
                this.funcsStore = {}
                res.funcs.forEach((func, index) => {
                  this.funcsFormat(func, index)
                })
              }
              this.funcs = res.funcs
              this.$refs.tree.setCheckedKeys(['nav_workbench'])
            }
          })
        }
      },
      getAutoqcAndVideoCheck (arr) {
        let flag = false
        let videoFlag = false
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].indexOf('autoqc') > -1) { // 智能質檢被選中
            flag = true
          }
          if (arr[i] === 'video_insert') { //视频设置被選中
            videoFlag = true
          }
          if (flag && videoFlag) {
            break
          }
        }
        this.autoqcCheck = flag
        this.videoSetCheck = videoFlag
      },
      funcsFormat (funcs, label) {
        let func = deepClone(funcs)
        func.label = label + ''
        this.funcsArray.push(func)
        this.funcsStore[funcs.id] = func
        if (func.children) {
          func.children.forEach((child, index) => {
            this.funcsFormat(child, label + '_' + index)
          })
        }
      },
      oldRoleFormat (limitsin, func) {
        console.time('权限处理耗时')
        let funsarray = deepClone(this.funcsArray).reverse()
        let array = funsarray.filter((fun) => {
          return limitsin.indexOf(fun.id) > -1
        })
        array.forEach((item) => {
          if (item.children) {
            this.checkFather(item.id, item.children)
          }
        })
        console.timeEnd('权限处理耗时')
      },
      removeFather (id) {
        this.limitStore.splice(this.limitStore.indexOf(id), 1)
        if (this.limitStore.indexOf(id) !== -1) {
          this.removeFather(id)
        }
      },
      checkFather (father, childrens) {
        let status = false
        childrens.forEach((child) => {
          if (this.limitStore.indexOf(child.id) === -1) {
            status = true
          }
          if (child.children) {
            this.checkFather(child.id, child.children)
          }
        })
        if (status && this.limitStore.indexOf(father) !== -1) {
          this.removeFather(father)
        }
      },
      checkAdvance () {
        // 判断目前选中的权限是否有老版高级功能下的权限，如果有，将高级功能字段加入权限数组，否则老版会出现没有高级功能入口的情况
        let advance = ['config_interface', 'system_notice', 'dic_config', 'nav_questionnaire', 'call_config', 'func_mark_cdr', 'monitor_log_record', 'call_sheet_export_monitor_task', 'call_sheet_leak']
        let status = false
        advance.forEach((item) => {
          if (this.limitStore.indexOf(item) > -1) {
            status = true
          }
        })
        if (status === true && this.limitStore.indexOf('advanced_config') === -1) {
          this.limitStore.push('advanced_config')
        }
      }
    },
    mounted () {
      this.getRoleDetails()
    }
  }
</script>

<style lang='stylus' scoped>
  @import "../../../../assets/common.styl"
  .roleEdit
    margin: 0 auto
    padding: 20px
    .header
      margin: 10px 0
      text-align right
      span
        float left
        margin-left 20px
    .el-form
      width 550px
      margin 0 auto
      .el-input, .el-textarea
        width 280px
      .scope
        margin: 5px 0
        span
          display inline-block
          width 70px
          margin-right 10px
        .el-select
          width 200px
      .tips
        color: #c09853;
        padding: 8px 35px 8px 14px;
        margin-bottom: 20px;
        text-shadow: 0 1px 0 rgba(255,255,255,0.5);
        background-color: #fcf8e3;
        border: 1px solid #fbeed5;
        border-radius: 4px;
      .icon-wenzishuoming
        font-size 12px
        margin-left 3px
</style>
